import paramiko
import csv
import os
import argparse
import subprocess
import sys

'''

from PyQt4 import QtGui
from PyQt4 import QtCore

useCustomConf = True
fileName = ''

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        
        self.setGeometry(200,200,350,300)
        self.setWindowTitle('N-Body Simulator')
        
        self.cb = QtGui.QCheckBox('Create a new configuration',self)
        self.cb.setFocusPolicy(QtCore.Qt.NoFocus)
        self.cb.setGeometry(10,10,200,25)
        self.cb.toggle()
        self.connect(self.cb,QtCore.SIGNAL('stateChanged(int)'),self.toggleConf)

        fileLabel = QtGui.QLabel('Use a configuration file from file:',self)
        fileLabel.setGeometry(10,30,300,20)

        self.filetb = QtGui.QLineEdit(self)
        self.filetb.setGeometry(10,50,250,25)
        self.connect(self.filetb,QtCore.SIGNAL('textChanged(QString)'),self.setFileName)

        self.fileButton = QtGui.QPushButton('Browse...',self)
        self.fileButton.setGeometry(260,50,75,25)
        self.connect(self. fileButton,QtCore.SIGNAL('clicked()'),self.openFileBrowser)

        serverLabel = QtGui.QLabel('Host name:',self)
        serverLabel.setGeometry(10,70,300,20)

        self.servertb = QtGui.QLineEdit(self)
        self.servertb.setGeometry(10,90,250,25)
        self.servertb.setText(d_server)
        
        userLabel = QtGui.QLabel('Username:',self)
        userLabel.setGeometry(10,110,100,20)
        
        self.usertb = QtGui.QLineEdit(self)
        self.usertb.setGeometry(10,130,120,25)
        
        passLabel = QtGui.QLabel('Password:',self)
        passLabel.setGeometry(140,110,100,20)
        
        self.passtb = QtGui.QLineEdit(self)
        self.passtb.setGeometry(140,130,120,25)
        #self.connect(self.passtb,QtCore.SIGNAL('textChanged(QString)'),self.securePassword)
        #self.password = ''
        
        dirLabel = QtGui.QLabel('Base directory:',self)
        dirLabel.setGeometry(10,150,300,20)
        
        self.dirtb = QtGui.QLineEdit(self)
        self.dirtb.setGeometry(10,170,250,25)
        self.dirtb.setText(d_directory)
        
        comLabel = QtGui.QLabel('Basic command:',self)
        comLabel.setGeometry(10,190,300,20)
        
        self.comtb = QtGui.QLineEdit(self)
        self.comtb.setGeometry(10,210,250,25)
        self.comtb.setText(d_command)
        
        self.endButton = QtGui.QPushButton('Continue',self)
        self.endButton.setGeometry(75,250,100,25)
        self.connect(self.endButton,QtCore.SIGNAL('clicked()'),self.endWindow)

    def toggleConf(self, value):
        global useCustomConf
        
        if self.cb.isChecked():
            useCustomConf = True
        else:
            useCustomConf = False

    def openFileBrowser(self):
        global fileName
        fileName = QtGui.QFileDialog.getOpenFileName(self,'Open file','/home')
        self.filetb.setText(fileName)
    
    def setFileName(self, text):
        global fileName
        fileName = text

    def endWindow(self):
        global useCustomConf
        global fileName
        
        if useCustomConf:
            #add calls for new class
            pass
        
        contactServer(self.servertb.text(),self.usertb.text(),self.passtb.text(),self.dirtb.text(),'out.csv',self.filetb.text(),self.comtb.text())
    
    '''
    '''
    def securePassword(self, text):
        t = str(text)
        if len(self.password) <= len(text):
            self.password = self.password + t[len(t)-1:len(t)]
        else:
            self.password = self.password[0:len(t)]
        
        temp = ''
        for i in range(len(self.password)):
            temp = temp + '*'
        
        self.passtb.setText(temp)
    '''
    '''

def getConfigurations():
    c = open('conf/defaults.conf','rb')
    
    reader = csv.reader(c)
    conf = reader.next()
    
    global d_server
    global d_directory
    global d_command
    
    d_server = conf[0]
    d_directory = conf[1]
    d_command = conf[2]

def contactServer(host, username, password, baseDir, outputFile, localFile, command):
    baseDir = baseDir + '/'
        
    print 'Transfering files...'
    try:
        transport = paramiko.Transport((str(host),22))

        transport.connect(username = username, password = password)
        sftp = paramiko.SFTPClient.from_transport(transport)          
        
        f = localFile.split('/')
        f = f[len(f) - 1]
        
        print localFile
        print baseDir + f
        
        sftp.put(str(localFile),str(baseDir + f))
        
        sftp.close()
        print 'Done.'
    except:
        print 'Error: cannot find server or ssh configuration is invalid!'
        quit()
                
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(str(host), username = str(username), password = str(password))
    
    #Need to actually use these vars to catch variables
    stdin, stdout, stderr = ssh.exec_command('cd ' + baseDir + ';' + command + ' < ' + f + ' > ' + outputFile)
    
    p = subprocess.Popen('python NBodyAnimate.py --host ' + host + ' --username ' + username + ' --password ' + password + ' --baseDir ' + baseDir + ' -g ' + baseDir + outputFile + ' -o ' + outputFile, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    print 1
    print 2
    
    ssh.close()

if __name__ == '__main__':
    getConfigurations()
    app = QtGui.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

'''

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Animates a gravitational n-body simulation.')
    parser.add_argument('-s','--ssh',dest='confFile',type=str,help='File that holds the ssh configuration.')
    parser.add_argument('-r','--remoteconf',dest='remoteConfFile',default='X',help='Remote location of the file for sim configuration.')
    parser.add_argument('-f','--file',dest='localFile',default='X',help='File that holds the configuration for the sim.')
    parser.add_argument('-o','--output',dest='outputFile',default='out.csv',help='File that will be output by the sim.')
    parser.add_argument('-t','--time',dest='time',default=100,help='Time to run the simulation. Defaults to 100')
    args = parser.parse_args()
    
    try:
        cFile = open(args.confFile, 'rb')
    except:
        print 'Error: invalid ssh configuration file!'
        quit()
        
    print 'Connecting to the ssh server...'
    
    reader = csv.reader(cFile)
    conf = reader.next()
    
    host = conf[0]
    port = conf[1]
    username = conf[2]
    password = conf[3]
    baseDir = conf[4]
    
    if not baseDir.rfind('/') == len(baseDir) - 1:
        baseDir = baseDir + '/'
    
    if args.remoteConfFile == 'X' and not args.localFile == 'X':
        print 'Transfering files...'
        try:
            transport = paramiko.Transport((host,int(port)))

            transport.connect(username = username, password = password)
            sftp = paramiko.SFTPClient.from_transport(transport)          
            
            fileName = args.localFile.split('/')
            fileName = fileName[len(fileName) - 1]
            
            sftp.put(args.localFile,baseDir + fileName)
            
            sftp.close()
            print 'Done.'
        except:
            print 'Error: cannot find server or ssh configuration is invalid!'
            quit()
            
    elif not args.remoteConfFile == 'X':
        pass
    else:
        print 'Error: failed to parse commands properly.'
        
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, username = username, password = password)
    
    #Need to actually use these vars to catch variables
    #stdin, stdout, stderr = ssh.exec_command('cd ' + baseDir + ';./NBody ' + args.localFile + ' ' + args.outputFile + ' -t ' + str(args.time))
    stdin, stdout, stderr = ssh.exec_command('cd ' + baseDir + ';./allpairs < ' + args.localFile + ' > ' + args.outputFile);
    
    p = subprocess.Popen('python NBodyAnimate.py -s ' + args.confFile + ' -g ' + baseDir + args.outputFile + ' -o ' + args.outputFile, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    #print 'python NBodyAnimate.py -s ' + args.confFile + ' -g ' + baseDir + args.outputFile + ' -o ' + args.outputFile
    p.wait()
    #print stdout.read()
    
    ssh.close()